package com.sqsf.test;
import com.alibaba.druid.pool.DruidDataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
@Configuration

//用于配置spring组件扫描 等价于<context:component-scan base-package="com.sqsf"/>
@ComponentScan("com.sqsf")

//当需要读取properties时
@PropertySource("classpath:jdbc.properties")
public class SpringConfig {
    //通过@Value注入属性
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    //对于自定义类型配置 书写方法返回对象交由spring容器管理
    @Bean("druid")
    public DruidDataSource druid(){
        DruidDataSource druid=new DruidDataSource();
        druid.setDriverClassName("com.mysql.jdbc.Driver");
        druid.setUrl("jdbc:mysql:///test");
        druid.setUsername("root");
        druid.setPassword("123456");
        return druid;
    }

    @Bean(name="c3p0")
    //创建指定id的bean
    public DataSource getDataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(driver);
        dataSource.setJdbcUrl(url);
        dataSource.setUser(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}
